import request from '@/utils/request'

// 随机题目筛选条件接口
export interface RandomQuestionFilters {
  difficulty?: string
  tags?: string[]
  category?: string
  solved?: boolean
  min_time_limit?: number
  max_time_limit?: number
  min_memory_limit?: number
  max_memory_limit?: number
}

// 随机题目响应接口
export interface RandomQuestionResponse {
  id: number
  title: string
  description: string
  difficulty: string
  tags: string
  category: string
  time_limit: number
  memory_limit: number
  is_solved: boolean
  attempt_count: number
  created_at: string
  updated_at: string
}

/**
 * 获取随机题目（简单筛选）
 * @param params 查询参数
 * @returns 随机题目信息
 */
export const getRandomQuestion = (params?: {
  difficulty?: string
  tags?: string
  category?: string
  solved?: boolean
}): Promise<RandomQuestionResponse | null> => {
  const queryParams = new URLSearchParams()
  
  if (params?.difficulty) {
    queryParams.append('difficulty', params.difficulty)
  }
  if (params?.tags) {
    queryParams.append('tags', params.tags)
  }
  if (params?.category) {
    queryParams.append('category', params.category)
  }
  if (params?.solved !== undefined) {
    queryParams.append('solved', params.solved.toString())
  }

  const url = `/v1/random-question${queryParams.toString() ? '?' + queryParams.toString() : ''}`
  
  return request.get(url).then(response => {
    const data = response.data
    if (data.success === false) {
      if (data.message === '没有符合条件的题目' || data.message === '没有找到符合条件的题目') {
        return null
      }
      throw new Error(data.message || '获取随机题目失败')
    }
    return data.data
  }).catch((error) => {
    console.error('获取随机题目失败:', error)
    throw error
  })
}

/**
 * 获取随机题目（复杂筛选）
 * @param filters 筛选条件
 * @returns 随机题目信息
 */
export const getRandomQuestionWithFilters = (filters: RandomQuestionFilters): Promise<RandomQuestionResponse | null> => {
  return request.post('/v1/random-question/filters', filters).then(response => {
    const data = response.data
    if (data.success === false) {
      if (data.message === '没有符合条件的题目' || data.message === '没有找到符合条件的题目') {
        return null
      }
      throw new Error(data.message || '获取随机题目失败')
    }
    return data.data
  }).catch((error) => {
    console.error('获取随机题目失败:', error)
    throw error
  })
}

/**
 * 获取随机题目（根据当前筛选条件）
 * @param currentFilters 当前页面的筛选条件
 * @returns 随机题目信息
 */
export const getRandomQuestionFromCurrentFilters = (currentFilters: any): Promise<RandomQuestionResponse | null> => {
  // 将当前筛选条件转换为API参数
  const filters: RandomQuestionFilters = {}
  
  if (currentFilters.difficulty) {
    filters.difficulty = currentFilters.difficulty
  }
  
  if (currentFilters.tags && currentFilters.tags.length > 0) {
    filters.tags = currentFilters.tags
  }
  
  if (currentFilters.category) {
    filters.category = currentFilters.category
  }
  
  if (currentFilters.solved !== undefined) {
    filters.solved = currentFilters.solved
  }
  
  if (currentFilters.timeLimit) {
    if (currentFilters.timeLimit.min) {
      filters.min_time_limit = currentFilters.timeLimit.min
    }
    if (currentFilters.timeLimit.max) {
      filters.max_time_limit = currentFilters.timeLimit.max
    }
  }
  
  if (currentFilters.memoryLimit) {
    if (currentFilters.memoryLimit.min) {
      filters.min_memory_limit = currentFilters.memoryLimit.min
    }
    if (currentFilters.memoryLimit.max) {
      filters.max_memory_limit = currentFilters.memoryLimit.max
    }
  }
  
  // 如果有复杂筛选条件，使用POST接口
  if (Object.keys(filters).length > 0) {
    return getRandomQuestionWithFilters(filters)
  } else {
    // 否则使用简单的GET接口
    return getRandomQuestion()
  }
}
